package com.resign.carl.lang;

import com.google.common.base.Objects;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by carl.zhao on 2016/6/14.
 */
public class EnumUtil {

    private EnumUtil() {}

    public static <K, E extends EnumCode<K>> E getEnumByKey(Class<E> clazz, K key) {
        if (Enum.class.isAssignableFrom(clazz)) {
            if (key == null) {
                return null;
            }
            E[] enumConstants = clazz.getEnumConstants();
            if (null != enumConstants && 0 != enumConstants.length) {
                for (E e : enumConstants) {
                    if (Objects.equal(e.getKey(), key)) {
                        return e;
                    }
                }
            }
            return null;
        }
        throw new ServiceException(RETURN_CODE.ARGS_ERROR, "类%s不是符合要求的枚举类");
    }

    public static <K, E extends EnumCode<K>> E getEnumByDescription(Class<E> clazz, String description) {
        if (Enum.class.isAssignableFrom(clazz)) {
            if (StringUtils.isEmpty(description)) {
                return null;
            }
            E[] enumConstants = clazz.getEnumConstants();
            if (null != enumConstants && 0 != enumConstants.length) {
                for (E e : enumConstants) {
                    if (StringUtils.equals(e.getDescription(), description)) {
                        return e;
                    }
                }
            }
            return null;
        }
        throw new ServiceException(RETURN_CODE.ARGS_ERROR, "类%s不是符合要求的枚举类");
    }
}
